module SpiTransmitter(
  iClk,
  oSclk,
  iMiso,
  oMosi,
  oCs,
  iData,
  oData,
  iStart,
  oBusy
);

input iClk, iMiso, iStart;
input[7:0] iData;
output reg oSclk = 0, oCs = 1, oBusy = 0;
output oMosi;
output reg[7:0] oData = 0;

// -------------- Parameters -----------------------
localparam DIV = 3;

// -------------- Internal registers and wires ----
reg prevStart = 0;
reg[7:0] shiftData = 0, inputData = 0;
reg [3:0] state = 0, cnt = 0;
reg clkDiv = 0;

// -------------- assign blocks --------------------
assign oMosi = shiftData[7];

// -------------- always blocks --------------------
always@(posedge iClk ) begin
  if(cnt >= DIV - 1) begin
    cnt <= 'd0;
    clkDiv <= ~clkDiv;
  end
  else cnt <= cnt + 1'd1;
end

always@(posedge clkDiv) begin
  prevStart <= iStart;
  if(!oBusy) begin    
    if({prevStart, iStart} == 2'b01) begin
      oBusy <= 'd1;
      oCs <= 'd0;
      shiftData <= iData;
      oSclk <= 'd0;
      state <= 'd7;
      inputData = 'd0;
    end
  end
  else begin
    if(oSclk) begin
      oSclk <= 'd0;
      shiftData <= {shiftData[6:0], 1'd0};
      state <= state - 1'd1;
      if(state == 'd0) begin
        oCs <= 'd1;
        oBusy <= 'd0;
        oData <= inputData;
      end
    end
    else begin
      oSclk <= 'd1;
      inputData <= {inputData[6:0], iMiso};
    end
  end
end

endmodule
